package com.qf.dao;

import com.qf.entity.Publist;
import com.qf.utils.DBHelper;

import javax.servlet.http.HttpServletRequest;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * 访问数据库 - 用户处理文章的查询和插入 修改
 */
public class PublishDao {
    public void insertPublist(Publist publist) {
    //     插入操作
        String sql = "insert into publist(N_createtime,N_nickname,N_content_text,N_content_img,N_sign) value (?,?,?,?,?)";
        DBHelper dbHelper = new DBHelper(sql);
        try {
            dbHelper.pst.setString(1,publist.getNCreatetime());
            dbHelper.pst.setString(2,publist.getNNickname());
            dbHelper.pst.setString(3,publist.getNContentText());
            dbHelper.pst.setString(4,publist.getNContentImg());
            dbHelper.pst.setString(5,publist.getNSign());
        //     执行sql语句的插入
            dbHelper.pst.executeUpdate();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            dbHelper.close();
        }

    }

    public List<Publist> queryPublist(HttpServletRequest req) {
        // 实例化一个数组 - 用存储查询到的数据
        ArrayList<Publist> publists = new ArrayList<>();
        // 区分你要查询的范围 - 查询所有 还是跟根据条件查询
        String nickname = req.getParameter("nickname");
        String sql = "";
        if(nickname.equals("all")){
            sql = "select * from publist";
        }else {
            sql = "select * from publist where N_nickname='"+nickname+"'";
        }
        // 调用数据库进行访问
        DBHelper dbHelper = new DBHelper(sql);
        // 开始查询
        try {
            ResultSet resultSet = dbHelper.pst.executeQuery();
            while (resultSet.next()){
                Publist publist = new Publist();
                publist.setNId(resultSet.getInt("N_id"));
                publist.setNContentText(resultSet.getString("N_content_text"));
                publist.setNCreatetime(resultSet.getString("N_createtime"));
                publist.setNNickname(resultSet.getString("N_nickname"));
                publist.setNContentImg(resultSet.getString("N_content_img"));
                publist.setNSign(resultSet.getString("N_sign"));
                publists.add(publist);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            dbHelper.close();
        }

        return publists;
    }

    public int delete_publish(String signD) {
        String sql = "delete from publist where N_sign='"+signD+"'";
        DBHelper dbHelper = new DBHelper(sql);
        int delete_int = 0;
        try {
            delete_int = dbHelper.pst.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            dbHelper.close();
        }

        return delete_int;
    }
}
